package com.dreamers.pathcore;

import com.dreamers.map.MapArray;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SaveManager {
    private static final String dataPath = "data/map.txt";
    private static final String SPLITSIGN = ",";
    private static final String CarriageReturn = "\r\n";
    static int[][] map = MapArray.map;

    public static void main(String[] args) {
        save();
        load();
    }

    public static void save() {
        File file = new File(dataPath);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            file.createNewFile();

            for (int i = 0; i < SaveManager.map.length; i++) {
                for (int j = 0; j < SaveManager.map[0].length; j++) {
                    fileWriter.write(SaveManager.map[i][j] + SPLITSIGN);
                    if (j == SaveManager.map[0].length - 1) {
                        fileWriter.write(SaveManager.map[i][j] + "");
                    } else {
                        fileWriter.write(SaveManager.map[i][j] + SPLITSIGN);
                    }
                }
                fileWriter.write(CarriageReturn);
            }
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static int[][] load() {
        try {
            File file = new File(dataPath);
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            List<List<String>> stringList = new ArrayList<>();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                String[] split = line.split(SPLITSIGN);
                stringList.add(Arrays.asList(split));
            }
            int height = stringList.size();
            int width = stringList.get(0).size();

            int[][] list = new int[height][width];

            for (int i = 0; i < stringList.size(); i++) {
                List<String> stringList1 = stringList.get(i);
                for (int j = 0; j < stringList1.size(); j++) {
                    list[i][j] = Integer.parseInt(stringList1.get(j));
                }
            }
            for (int i = 0; i < list.length; i++) {
                for (int j = 0; j < list[0].length; j++) {
                    System.out.print(list[i][j]);
                }
                System.out.println();
            }
            return list;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return new int[0][];
    }
}
